import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import type { RootState } from '@/types/store'

// type Ks = keyof RootState

/**
 * 进入页面时，获取数据
 * @param action 获取数据的 action 函数
 * @param stateName 获取状态的名称，对应 RootState 中某个状态名称
 * @return 要获取的状态
 */
export const useInitialState = <StateName extends keyof RootState>(
  action: () => void,
  stateName: StateName
): RootState[StateName] => {
  const dispatch = useDispatch()
  // 注意：此处访问对象 state 中的属性，应该使用 state[stateName] 来访问
  const state = useSelector((state: RootState) => state[stateName])
  // const state = useSelector<RootState, RootState[StateName]>(
  //   state => state[stateName]
  // )

  useEffect(() => {
    dispatch(action())
  }, [dispatch, action])

  return state
}
